package de.geckocraft.iConomyExchange.commands;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

import de.geckocraft.iConomyExchange.main.ExServer;
import de.geckocraft.iConomyExchange.main.configbymysql;
import de.geckocraft.iConomyExchange.main.main;
import de.geckocraft.iConomyExchange.main.template;

public class CommandsMain implements CommandExecutor
{

	private main plugin;

	public CommandsMain(main plugin)
	{
		this.plugin = plugin;
	}

	public boolean onCommand(CommandSender sender, Command cmd,
			String cmdLabel, String[] args)
	{

		if (!(sender instanceof Player))
		{
			sender.sendMessage(ChatColor.RED + "Sie sind kein Spieler!");
			return true;
		}

		Player p = (Player) sender;
		if (cmd.getName().equalsIgnoreCase("exchange"))
		{
			if (args.length > 0)
			{

				if (args[0].equalsIgnoreCase("reload"))
				{
					if(p.hasPermission("icomomyexchange.exchange.reload"))
					{
						main.loadconfig();
						template.sendMessage("reload", p, new String[0]);
						return true;
					}
					return false;
				} else if (args.length > 2)
				{
					
					@SuppressWarnings("unused")
					BukkitTask task = new ExampleTask(this.plugin, p, args)
							.runTaskLater(this.plugin, 0);
							
				}

			}
		}
		return false;
	}
	
	public class ExampleTask extends BukkitRunnable
	{
		
		@SuppressWarnings("unused")
		private final JavaPlugin plugin;
		private Player pt;
		private String[] argst;

		public ExampleTask(JavaPlugin plugin, Player p, String[] args)
		{
			this.plugin = plugin;
			pt = p;
			argst = args;
		}

		public void run()
		{
			exchange(pt, argst);
		}

	}

	private void exchange(Player p, String[] args)
	{
		if (p.hasPermission("icomomyexchange.exchange." + args[0].toLowerCase()
				+ "." + args[1].toLowerCase()))
		{
			ArrayList<ExServer> Servername1List = configbymysql.getExServers();
			Iterator<ExServer> exsinter = Servername1List.iterator();
			
			boolean args0bool = false;
			
			while (exsinter.hasNext())
			{
				// /exchange esconia stadt 10
				ExServer exs = exsinter.next();

				if (args[0].equalsIgnoreCase(exs.getName()))
				{
					args0bool = true;
					ResultSet rsGeld = exs.sendStatement("select "+ exs.Balancetabellenname +".balance from "
							+ exs.Accounttabellenname + ", "+exs.Balancetabellenname +" where "+ exs.Accounttabellenname + ".name = '"
							+ p.getName() + "' and " + exs.Balancetabellenname + ".username_id = " + exs.Accounttabellenname + ".id");

					// gucken ob der Spieler auf Server 1 exestiert
					if (rsGeld != null)
					{

						try
						{
							rsGeld.next();
							Double ismoney = rsGeld.getDouble(1);
							
							if(main.parseDouble(args[2]))
							{
								
								Double minusmoney = Double.parseDouble(args[2]);
	
								// gucken ob der Spieler genug geld hat
								if (ismoney > minusmoney)
								{
									
									// gucken ob der Spieler auf Server 2 exestier
									Iterator<ExServer> exsinter2 = Servername1List
											.iterator();
									boolean args1bool = false;
									while (exsinter2.hasNext())
									{
	
										ExServer exs2 = exsinter2.next();
										if (args[1]
												.equalsIgnoreCase(exs2.getName()))
										{
											args1bool = true;
	
											ResultSet rsGeld2 = exs2
													.sendStatement("select "+ exs2.getBalancetabellenname() +".balance from "
															+ exs2.getAccounttabellenname() + ", "+exs2.getBalancetabellenname() +" where "+ exs2.getAccounttabellenname() + ".name = '"
															+ p.getName() + "' and " + exs2.getBalancetabellenname() + ".username_id = " + exs2.getAccounttabellenname() + ".id");
											rsGeld2.next();
											String stringmoney2 = rsGeld2
													.getString(1);
											if (stringmoney2 != null)
											{
	
												Double ismoney2 = Double
														.parseDouble(stringmoney2);
	
												Double newmoney1 = ismoney
														- minusmoney;
												exs.sendUpdate("update "
														+ exs.getBalancetabellenname()
														+ " set balance ="
														+ newmoney1.toString()
														+ " where username_id = (select id from " + exs.getAccounttabellenname() + " where name = '" + p.getName() + "') and balance >= " + args[2]);
	
												HashMap<String, Double> hashwech = exs
														.getWechselkurs();
												Double kurs = hashwech.get(args[1]
														.toLowerCase());
												Double plusmoney = minusmoney * kurs;
												Double newmoney2 = ismoney2
														+ plusmoney;
												exs2.sendUpdate("update "
														+ exs2.getBalancetabellenname()
														+ " set balance="
														+ newmoney2.toString()
														+ "  where username_id = (select id from " + exs2.getAccounttabellenname() + " where name = '" + p.getName() + "')");
												
												template.sendMessage("changed", p, new String[] {minusmoney.toString(), exs.getWaehrung(),plusmoney.toString(),exs2.getWaehrung() });
												
	
											}
											else
											{
												template.sendMessage("noacc", p, new String[] { args[1] });
											}
										}
									}
									if(!args1bool)
									{
										template.sendMessage("noserver", p, new String[] { args[1] });
									}
	
								} else
								{
									template.sendMessage("nomoney", p,
											new String[0]);
								}
							}
						else
						{
							template.sendMessage("nodouble", p, new String[] { args[2] });
						}

						} catch (SQLException e)
						{
							e.printStackTrace();
						}
					} else
					{
						template.sendMessage("nomoney", p, new String[0]);
					}
				}
			}
			if(!args0bool)
			{
				template.sendMessage("noserver", p, new String[] { args[0] });
			}

		} else
		{
			template.sendMessage("nopermission", p, new String[0]);
		}
	
	}
}
